import React, {FC} from 'react';
import {ComponentConfType, componentGroup} from "../../../components/QuestionComponents";
import {Typography} from "antd";
import style from './ComponentLib.module.scss'
import {useDispatch} from "react-redux";
import {addComponent} from "../../../redux/componentsReducer";
import {nanoid} from "@reduxjs/toolkit";

const {Title} = Typography
const ComponentLib: FC = () => {
    const dispatch = useDispatch()

    // 获取组件，并为点击组件添加方法
    function getComponent(c: ComponentConfType) {
        const {Component, title, type, defaultProps} = c

        function handleClick() {
            dispatch(addComponent({
                fe_id: nanoid(),
                type,
                title,
                props: defaultProps
            }))
        }

        return <div key={type} className={style.wrapper} onClick={handleClick}>
            <div className={style.component}>
                <Component/>
            </div>
        </div>
    }

    return (
        <div>
            {
                componentGroup.map((item, index) => {
                    const {groupId, groupName, components} = item
                    return <div key={groupId}>
                        <Title level={3}
                               style={{fontSize: '16px', marginTop: index > 0 ? '20px' : ''}}>{groupName}</Title>
                        <div>
                            {
                                components.map(c => getComponent(c))
                            }
                        </div>
                    </div>
                })
            }
        </div>
    );
};

export default ComponentLib;
